package com.hzw.net.net.upload

import okhttp3.MediaType
import okhttp3.RequestBody
import okio.*

/**
 *
 * @Author:         HuaZhongWei
 * @CreateDate:     2020/7/1 10:05
 *
 * @Description:
 *
 */
class RequestBodyWithProgress(
    private val requestBody: RequestBody,
    private val listener: OnUploadListener? = null
) : RequestBody() {

    private lateinit var bufferSink: BufferedSink

    override fun contentType(): MediaType? = requestBody.contentType()

    override fun contentLength(): Long = requestBody.contentLength()

    override fun isDuplex(): Boolean {
        return requestBody.isDuplex()
    }

    override fun isOneShot(): Boolean {
        return requestBody.isOneShot()
    }

    override fun writeTo(sink: BufferedSink) {
        if (!this::bufferSink.isInitialized) {
            bufferSink = object : ForwardingSink(sink) {
                val total by lazy {
                    contentLength()
                }
                var current = 0L
                override fun write(source: Buffer, byteCount: Long) {
                    super.write(source, byteCount)
                    listener?.let {
                        current += byteCount
                        it.onUpload(current, total, current == total)
                    }
                }
            }.buffer()
        }
        requestBody.writeTo(bufferSink)
        bufferSink.flush()
    }
}